import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import { Form, Icon, Input, Button, Checkbox, Row, Col, message } from 'antd';
import { connect } from 'react-redux';
import { LOGIN_REQUEST, LOGIN_FAILURE } from 'actions';
import * as globals from 'globals';

message.config({
    duration: globals.message_duration,
});
message.config({
    duration: globals.message_duration,
});

class SignInForm extends Component {
  static propTypes = {
    history: PropTypes.object.isRequired,
  }

  handleSubmit(event) {
    event.preventDefault();
    this.props.form.validateFieldsAndScroll((error, values) => {
      if(!error) {
        // 开始请求后台
        this.props.dispatch({type: LOGIN_REQUEST, ...values});
      }
    });
  }
  render() {
    const { getFieldDecorator } =  this.props.form;
    return(
      <Form onSubmit={this.handleSubmit.bind(this)}>
        <Form.Item>
          {
            getFieldDecorator('username', {
              rules: [{ required: true, message: '请输入用户名' }],
            })(
              <Input prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="用户名" />
            )
          }
        </Form.Item>
        <Form.Item>
          {
            getFieldDecorator('password', {
              rules: [{ required: true, message: '请输入密码' }]
            })(
              <Input type="password" prefix={<Icon type="lock" style={{ fontSize: 13 }} />} placeholder="密码" />
            )
          }
        </Form.Item>
        <Form.Item>
          <Checkbox>记住密码</Checkbox>
          <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
            登录
          </Button>
        </Form.Item>
      </Form>
    );
  }

  componentDidUpdate() {
    if(this.props.data !== null) {
      message.success('登录成功,正在跳转到首页...');
      setTimeout(() => {
        this.props.history.push('/');
      }, globals.message_duration * 1000);
    } else if(this.props.error !== null) {
      message.error('登录错误，' + this.props.error);
      this.props.dispatch({ type: LOGIN_FAILURE, data: null, error: null });
    }
  }
}

const mapStateToProps = (state) => {
  return {
    loading: state.login.loading,
    data: state.login.data,
    error: state.login.error,
  };
};

export default connect(mapStateToProps)(Form.create()(SignInForm));
